<?php

namespace app\controllers;

use app\common\utils\HttpClient;
use app\models\GkyWeAccount;
use Yii;
use app\models\GkyWeFans;
use app\models\GkyWeFansSearch;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;

/**
 * GkyWeFansController implements the CRUD actions for GkyWeFans model.
 */
class GkyWeFansController extends Controller
{
    public $enableCsrfValidation = false;
     public $layout='main_1';
    public function behaviors()
    {
        return [
            'verbs' => [
                'class' => VerbFilter::className(),
                'actions' => [
                    'delete' => ['post'],
                ],
            ],
        ];
    }

    /**
     * Lists all GkyWeFans models.
     * @return mixed
     */
    public function actionIndex()
    {

        $searchModel = new GkyWeFansSearch();
        $dataProvider = $searchModel->search(Yii::$app->request->queryParams);

        return $this->render('index', [
            'searchModel' => $searchModel,
            'dataProvider' => $dataProvider,
        ]);
    }
    public function actionGetUserOpenid($code){
        $appID=  \app\api\Constant::$WE_APPID;
        $secret=  \app\api\Constant::$WE_SECRET;
        $url="https://api.weixin.qq.com/sns/oauth2/access_token?appid=$appID&secret=$secret&code=$code&grant_type=authorization_code";
        $result=  HttpClient::get($url);
        header("Access-Control-Allow-Origin: *");
        echo json_encode($result);
    }
    public function actionGetUserInfo($openid){
        $access_token=  GkyWeAccount::findOne(['id'=>5])->getToken();
        $url="https://api.weixin.qq.com/cgi-bin/user/info?access_token=$access_token&openid=$openid&lang=zh_CN";
        $result=  HttpClient::get($url);
//        echo $access_token;
        header("Access-Control-Allow-Origin: *");
        echo json_encode($result);
    }

    /**
     * 刷新粉丝数据
     */
    public function actionRefresh(){

        $weaccount = Yii::$app->session->get('weixin');
        if($weaccount == null){
            return $this->actionIndex();
        }
        $url = 'https://api.weixin.qq.com/cgi-bin/user/get?access_token='.$weaccount->token.'&next_openid=';
        $result = HttpClient::get($url);
        if($result == null || $result -> data == null){
            return $this->actionIndex();
        }
        $user_list = [];
        foreach($result->data->openid as $openid){
            $fans = [
                'openid' => $openid,
                'lang'   => 'zh-CN'
            ];
            $user_list[] = $fans;
        }

        $post_data = json_encode([
            'user_list' => $user_list
        ]);

        $fansURL = 'https://api.weixin.qq.com/cgi-bin/user/info/batchget?access_token='.$weaccount->accesstoken;
        $fansList = HttpClient::post($fansURL, $post_data);
        foreach($fansList->user_info_list as $user_info){

            $wefans = GkyWeFans::find()
                ->where(['openid'=>$user_info -> openid, 'weid'=> $weaccount->id])
                ->one();
            if($wefans == null){
                $wefans = new GkyWeFans();
            }
            $wefans -> weid = $weaccount -> id;
            $wefans -> wename = $weaccount -> wename;
            $wefans -> openid = $user_info -> openid;
            $wefans -> nickname = $user_info -> nickname;
            $wefans -> sex = $user_info -> sex == 1 ? '男' : '女';
            $wefans -> language = $user_info -> language;
            $wefans -> city = $user_info -> city;
            $wefans -> province = $user_info -> province;
            $wefans -> country = $user_info -> country;
            $wefans -> headimgurl = $user_info -> headimgurl;
            $wefans -> subscribe_time = date('Y-m-d H:i:s',$user_info -> subscribe_time);
            $wefans -> remark = $user_info -> remark;
            $wefans -> groupid = $user_info -> groupid;
            $wefans->save();
        }

        return $this->actionIndex();
    }

    /**
     * Displays a single GkyWeFans model.
     * @param string $id
     * @return mixed
     */
    public function actionView($id)
    {
        return $this->render('view', [
            'model' => $this->findModel($id),
        ]);
    }

    /**
     * Creates a new GkyWeFans model.
     * If creation is successful, the browser will be redirected to the 'view' page.
     * @return mixed
     */
    public function actionCreate()
    {
        $model = new GkyWeFans();

        if ($model->load(Yii::$app->request->post()) && $model->save()) {
            return $this->redirect(['view', 'id' => $model->id]);
        } else {
            return $this->render('create', [
                'model' => $model,
            ]);
        }
    }

    /**
     * Updates an existing GkyWeFans model.
     * If update is successful, the browser will be redirected to the 'view' page.
     * @param string $id
     * @return mixed
     */
    public function actionUpdate($id)
    {
        $model = $this->findModel($id);

        if ($model->load(Yii::$app->request->post()) && $model->save()) {
            return $this->redirect(['view', 'id' => $model->id]);
        } else {
            return $this->render('update', [
                'model' => $model,
            ]);
        }
    }

    /**
     * Deletes an existing GkyWeFans model.
     * If deletion is successful, the browser will be redirected to the 'index' page.
     * @param string $id
     * @return mixed
     */
    public function actionDelete($id)
    {
        $this->findModel($id)->delete();

        return $this->redirect(['index']);
    }

    /**
     * Finds the GkyWeFans model based on its primary key value.
     * If the model is not found, a 404 HTTP exception will be thrown.
     * @param string $id
     * @return GkyWeFans the loaded model
     * @throws NotFoundHttpException if the model cannot be found
     */
    protected function findModel($id)
    {
        if (($model = GkyWeFans::findOne($id)) !== null) {
            return $model;
        } else {
            throw new NotFoundHttpException('The requested page does not exist.');
        }
    }
}
